export class TimeUtils {
    /** 服务器时间差(秒级) */
    serverTimeDtSecond: number = 0;

    /** 获取服务器时间
     * @returns {number} 服务器时间
     */
    getServerTime(): number {
        const timeStamp = Date.now() / 1000;
        return timeStamp - this.serverTimeDtSecond;
        return timeStamp
    }

    /** 设置服务器时间差
     * @param {number} serverTimeStampSecond 服务器时间戳
     * @param {number} clientReqTimeSecond 客户端请求时间戳
     */
    updateServerTimeDt(serverTimeStampSecond: number, clientReqTimeSecond: number): void {
        const dt1 = clientReqTimeSecond - serverTimeStampSecond;
        const dt2 = (Date.now() / 1000) - serverTimeStampSecond;
        if (Math.abs(dt1 - dt2) > 1000) {
            if (Math.abs(dt1) < Math.abs(dt2)) { //取延迟时间更小的那个
                this.serverTimeDtSecond = dt1;
            } else {
                this.serverTimeDtSecond = dt2;
            }
        } else {
            this.serverTimeDtSecond = dt1 + dt2 / 2;
        }
        this.serverTimeDtSecond = dt1
        console.log(`更新服务器时间差: ${this.serverTimeDtSecond}`);
    }
}